package com.base.service;

import com.base.entity.OrderEntity;
import com.base.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames="my-redis-cache1")
public class OrderService {

    @Autowired
    public OrderRepository orderRepository;

    @CachePut(value = "orderEntity", key = "#orderEntity.orderId")
    //如果有@CachePut的value值，则@CacheConfig的cacheNames会失效，redis 的eky 形如：orderEntity::orderid1589624644057
    //@CachePut 无论怎样，都将方法的返回结果放到缓存当中。
    public OrderEntity save(OrderEntity orderEntity) {
        return orderRepository.save(orderEntity);
    }

    @Cacheable  //开启缓存
    //redis 中保存的key 则形如: my-redis-cache1::com.base.service.OrderServicefindByOrderIdorderid1589620203270
    public OrderEntity findByOrderId(String id) {
        return orderRepository.findByOrderId(id);
    }

    @Cacheable(cacheNames = "orders", key = "'findByOrderId1'")
    //如果key 不加单引号，则报错：
    //EL1008E: Property or field 'findByOrderId1' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public or not valid?
    public OrderEntity findByOrderId1(String id) {
        return orderRepository.findByOrderId(id);
    }

    public List<OrderEntity> findAll() {
        return orderRepository.findAll();
    }
}
